<?php
uses('model');

class smsModel extends Model {

    function __construct() {
        parent::__construct();
    }

    function sendSms($v=null) {
        $this->debugmsg('smsModel::sendSms');
        $this->dbconnect();

        /*
        1.发送成功
        2.发送失败
        4.没有要发送的sms
        */

        $row = $this->db->GetAll($this->table['sms'], '*', 'issend = 0 AND err <> -1 AND sendtime < ' .time(). ' ORDER BY id');

        if ($row) {
            uses('sms');
            $m = new Sms;

            foreach ($row as $rs) {
                $m->setMsg($rs['msg']);
                $err = $m->sendMsg($rs['mobile'], '', false);

                if ($err === true) {
                    $data['code']['sendSms'] = 1;
                    //发送成功
                    $this->db->Update($this->table['sms'], array('issend'=>1), "id={$rs['id']}");
                } else {
                    $data['code']['sendSms'] = 2;
                    $data['err'] = $err; //错误原因

                    //发送失败的十五分钟后再发
                    $fields['sendtime'] = time() + 900;
                    $fields['err']      = '{[+1]}';
                    $fields['errmsg']   = iconv('GB2312', 'UTF-8', $err);
                    $this->db->Update($this->table['sms'], $fields, "id={$rs['id']}");
                }
            }

            //失败大于三次的不再发送
            $this->db->Update($this->table['sms'], array('issend'=>'-1'), "err >= 3");
        } else {
            $data['code']['sendSms'] = 4;
        }

        return $data;
    }
}
?>